package org.qiyu.live.im.provider.service.impl;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.idea.qiyu.live.framework.redis.starter.key.ImProviderCacheKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.qiyu.live.im.provider.service.ImTokenService;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-08
 * Time: 18:59
 */
@Service
public class ImTokenServiceImpl implements ImTokenService {

    private Logger LOGGER = LoggerFactory.getLogger(ImTokenServiceImpl.class);

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private ImProviderCacheKeyBuilder cacheKeyBuilder;

    @Override
    public String createImToken(Long userId, int appId) {
        if(userId == null || appId < 10000) {
            LOGGER.error("userId or appId error userId is {} , appId is {} ",userId,appId);
            return null;
        }
        // 1. 生成token
        String token = UUID.randomUUID() + "%" + appId;
        String key = cacheKeyBuilder.buildImTokenKey(token);
        // 2. 保存到redis中
        redisTemplate.opsForValue().set(key, String.valueOf(userId),5, TimeUnit.MINUTES);
        // 3. 返回token
        return token;
    }

    @Override
    public Long getUserIdByToken(String token) {
        if(StrUtil.isEmpty(token)) {
            LOGGER.error("token empty token is {}",token);
            return null;
        }
        // 1. 得到redis的key
        String key = cacheKeyBuilder.buildImTokenKey(token);
        // 2. 从redis中获取UserId
        Integer userId = (Integer) redisTemplate.opsForValue().get(key);
        return userId == null ? null : Long.valueOf(userId);
    }
}